package com.ihg.hiex.admin.web.controller.session.during;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.ihg.hiex.admin.entity.dto.ReportComment;
import com.ihg.hiex.admin.entity.security.Login;
import com.ihg.hiex.admin.service.session.SessionDuringService;
import com.ihg.hiex.admin.service.session.SessionMeetingService;
import com.ihg.hiex.admin.service.session.SessionParticipatorService;
import com.ihg.hiex.admin.service.session.SessionReportService;
import com.ihg.hiex.admin.service.session.SessionService;
import com.ihg.hiex.admin.service.session.SessionTaskService;
import com.ihg.hiex.admin.web.resolver.Secure;
import com.ihg.hiex.entity.session.Session;
import com.ihg.hiex.entity.session.during.SessionCalibration;
import com.ihg.hiex.entity.session.during.SessionCalibrationAnchorScore;
import com.ihg.hiex.entity.session.during.SessionCalibrationComment;
import com.ihg.hiex.entity.session.during.SessionCalibrationCompetency;
import com.ihg.hiex.entity.session.during.SessionCalibrationRecommendation;
import com.ihg.hiex.entity.session.during.report.SessionReportComment;
import com.ihg.hiex.entity.session.during.report.SessionReportRecommendation;
import com.ihg.hiex.entity.session.during.report.SessionReportWriting;
import com.ihg.hiex.entity.session.meeting.SessionMeeting;
import com.ihg.hiex.entity.session.participator.SessionParticipator;
import com.ihg.hiex.entity.session.participator.Type;
import com.ihg.hiex.entity.session.task.Status;
import com.ihg.hiex.entity.user.Delegate;

/**
 * 
 * @author dan
 *
 */
@Controller
@RequestMapping("/sessions/{sessionId}/supervisor-calibrations")
@MenuSetting("menu-home")
public class SupervisorCalibrationController {
    
    @Autowired
    private SessionService sessionService;
    
    @Autowired
    private SessionDuringService sessionDuringService;
    
    @Autowired
    private SessionParticipatorService sessionParticipatorService;
    
    @Autowired
    private SessionTaskService sessionTaskService;
    
    @Autowired
    private SessionMeetingService sessionMeetingService;
    
    @Autowired
    private SessionReportService sessionReportService;
    
    /**
     * 
     * @param login
     * @param sessionId
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(path = "", method = RequestMethod.GET)
    public ModelAndView list(@Secure Login login, @PathVariable("sessionId") Long sessionId) {
        
        ModelAndView modelAndView = new ModelAndView("session/during/peer-calibration/supervisor-calibration-list");
        
        Session session = sessionService.load(sessionId);
        modelAndView.addObject("session", session);
        
        // list assessor subgroup's delegates
        List<SessionParticipator> sessionParticipators = sessionParticipatorService.list(session);
        List<Long> delegateIds = CollectionUtils.extractPropertyList(sessionParticipators, "delegateId");
        
        // load meeting
        SessionMeeting sessionMeeting = sessionMeetingService.load(session, "Peer Calibration", login.getId());
        modelAndView.addObject("sessionMeeting", sessionMeeting);
        
        // list sessionCalibration by delegates
        List<SessionCalibration> sessionCalibrations = sessionDuringService.listSessionCalibration(session, delegateIds);
        modelAndView.addObject("sessionCalibrations", sessionCalibrations);
        
        // list sessionCalibrationCompetencies
        Map<String, Map<String, SessionCalibrationCompetency>> sessionCalibrationCompetencies = sessionDuringService.listSessionCalibrationCompetency(sessionCalibrations);
        modelAndView.addObject("sessionCalibrationCompetencies", sessionCalibrationCompetencies);
        
        // load sessionCalibrationComment
        Map<String, SessionCalibrationComment> sessionCalibrationComments = sessionDuringService.listSessionCalibrationComment(sessionCalibrations);
        modelAndView.addObject("sessionCalibrationComments", sessionCalibrationComments);
        
        // load sessionCalibrationRecommendation
        Map<String, SessionCalibrationRecommendation> sessionCalibrationRecommendations = sessionDuringService.listSessionCalibrationRecommendation(sessionCalibrations);
        modelAndView.addObject("sessionCalibrationRecommendations", sessionCalibrationRecommendations);
        
        List<Delegate> delegates = CollectionUtils.extractPropertyList(sessionCalibrations, "delegate");
        Map<Long, Status> reportTaskStatus = sessionTaskService.listCalibrationReportStatus(delegates, session, Type.ASSESSOR, new String[]{"Peer Calibration Competency", "Peer Calibration Comments", "Peer Calibration Recommendation"}, "Peer Calibration");
        modelAndView.addObject("reportTaskStatus", reportTaskStatus);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param login
     * @param sessionId
     * @param calibrationId
     * @return
     */
    @RequestMapping(path = "/{calibrationId}/report-writing", method = RequestMethod.GET)
    public ModelAndView reportWriting(@Secure Login login,
                                      @PathVariable("sessionId") Long sessionId,
                                      @PathVariable("calibrationId") Long calibrationId) {
        
        ModelAndView modelAndView = new ModelAndView("session/during/peer-calibration/supervisor-calibration-report-writing");
        
        SessionCalibration sessionCalibration = sessionDuringService.loadSessionCalibration(calibrationId);
        modelAndView.addObject("sessionCalibration", sessionCalibration);
        
        List<SessionCalibrationCompetency> competencies = sessionDuringService.listSessionCalibrationCompetency(sessionCalibration);
        modelAndView.addObject("competencies", competencies);
        
        SessionCalibrationComment comment = sessionDuringService.loadSessionCalibrationComment(sessionCalibration);
        modelAndView.addObject("comment", comment);
        
        SessionCalibrationRecommendation recommendation = sessionDuringService.loadSessionCalibrationRecommendation(sessionCalibration);
        modelAndView.addObject("recommendation", recommendation);
        
        SessionReportWriting sessionReportWriting = sessionReportService.loadReportWriting(sessionCalibration);
        modelAndView.addObject("sessionReportWriting", sessionReportWriting);
        
        // load sessionCalibrationCompetency
        List<SessionCalibrationCompetency> sessionCalibrationCompetencies = sessionDuringService.listSessionCalibrationCompetency(sessionCalibration);
        modelAndView.addObject("sessionCalibrationCompetencies", sessionCalibrationCompetencies);
        
        // list strength and development needs anchorScore
        Map<String, Map<String, List<SessionCalibrationAnchorScore>>> anchorScores = sessionDuringService.listSessionCalibrationAnchorScore(sessionCalibrationCompetencies);
        modelAndView.addObject("anchorScores", anchorScores);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param sessionId
     * @param calibrationId
     * @param language
     * @return
     */
    @MenuSetting(value = "submenu-session-during-development-day")
    @RequestMapping(value = "/{calibrationId}/edit-readiness-recommendation", method = RequestMethod.GET)
    public ModelAndView editReadinessRecommendation(@Secure Login login,
                                                    @PathVariable("sessionId") Long sessionId, 
                                                    @PathVariable("calibrationId") Long calibrationId,
                                                    @RequestParam(name = "language", required = false, defaultValue = "cn") String language) {
        
        ModelAndView modelAndView = new ModelAndView("session/during/development-day/readiness-recommendation-supervisor-edit");
        SessionCalibration sessionCalibration = sessionDuringService.loadSessionCalibration(calibrationId);
        modelAndView.addObject("sessionCalibration", sessionCalibration);
        
        SessionReportWriting sessionReportWriting = sessionReportService.loadReportWriting(sessionCalibration);
        modelAndView.addObject("sessionReportWriting", sessionReportWriting);
        
        if(sessionReportWriting == null) {
            SessionCalibrationRecommendation sessionCalibrationRecommendation = sessionDuringService.loadSessionCalibrationRecommendation(sessionCalibration);
            modelAndView.addObject("sessionCalibrationRecommendation", sessionCalibrationRecommendation);
        }
        
        modelAndView.addObject("session", sessionCalibration.getSession());
        modelAndView.addObject("language", language);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param sessionId
     * @param calibrationId
     * @param recommendation
     * @return
     */
    @RequestMapping(path = "/{calibrationId}/edit-readiness-recommendation", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEditReadinessRecommendation(@Secure Login login,
                                                                  @PathVariable("sessionId") Long sessionId,
                                                                  @PathVariable("calibrationId") Long calibrationId,
                                                                  SessionReportRecommendation recommendation) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            SessionCalibration sessionCalibration = sessionDuringService.loadSessionCalibration(calibrationId);
            
            sessionDuringService.editRecommendation(sessionCalibration, recommendation, login);
            
            httpResult.success().message("Successed");
            
        } catch (Exception e) {
            httpResult.fail("500").message("Failed");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param login
     * @param sessionId
     * @param calibrationId
     * @return
     */
    @MenuSetting(value = "submenu-session-during-development-day")
    @RequestMapping(value = "/{calibrationId}/edit-recommendations", method = RequestMethod.GET)
    public ModelAndView editRecommendations(@Secure Login login, @PathVariable("sessionId") Long sessionId, @PathVariable("calibrationId") Long calibrationId) {
        
        ModelAndView modelAndView = new ModelAndView("session/during/development-day/development-recommendations-supervisor-edit");
        
        SessionCalibration sessionCalibration = sessionDuringService.loadSessionCalibration(calibrationId);
        modelAndView.addObject("sessionCalibration", sessionCalibration);
        
        SessionReportWriting sessionReportWriting = sessionReportService.loadReportWriting(sessionCalibration);
        modelAndView.addObject("sessionReportWriting", sessionReportWriting);
        
        if(sessionReportWriting == null) {
            // load sessionCalibrationCompetency
            List<SessionCalibrationCompetency> sessionCalibrationCompetencies = sessionDuringService.listSessionCalibrationCompetency(sessionCalibration);
            modelAndView.addObject("sessionCalibrationCompetencies", sessionCalibrationCompetencies);
            
            SessionCalibrationComment comment = sessionDuringService.loadSessionCalibrationComment(sessionCalibration);
            modelAndView.addObject("comment", comment);
            
            Map<String, SessionCalibrationCompetency> competency = CollectionUtils.constructMapValue(sessionCalibrationCompetencies, "name");
            modelAndView.addObject("competency", competency);
        }
        
        modelAndView.addObject("id", sessionId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param calibrationId
     * @param comment
     * @param reportComment
     * @return
     */
    @RequestMapping(value = "/{calibrationId}/edit-recommendations" , method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onRecommendationSubmit(@Secure Login login,
                                                           @PathVariable("calibrationId") Long calibrationId,
                                                           SessionReportComment comment,
                                                           ReportComment reportComment) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            SessionCalibration sessionCalibration = sessionDuringService.loadSessionCalibration(calibrationId);
            
            sessionDuringService.editComment(sessionCalibration, comment, reportComment.getChooseComment(), login);
            
            httpResult.success().message("Successful");
            
        } catch (Exception e) {
            
            httpResult.fail("500").message("Failed");
            
        }
        return httpResult;
    }
    
    /**
     * 
     * @param login
     * @param sessionId
     * @param calibrationId
     * @return
     */
    @RequestMapping(value = "/{calibrationId}/report-submit", method = RequestMethod.GET)
    public ModelAndView submitReport(@Secure Login login, @PathVariable("sessionId") Long sessionId, @PathVariable("calibrationId") Long calibrationId) {
        
        ModelAndView modelAndView = new ModelAndView("session/during/development-day/supervisor-report-submit");
        
        SessionCalibration sessionCalibration = sessionDuringService.loadSessionCalibration(calibrationId);
        modelAndView.addObject("sessionCalibration", sessionCalibration);
        
        return modelAndView;
        
    }
    
    
    /**
     * 
     * @param login
     * @param sessionId
     * @param calibrationId
     * @return
     */
    @RequestMapping(value = "/{calibrationId}/report-submit", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onSubmitReport(@Secure Login login,
                                                   @PathVariable("sessionId") Long sessionId,
                                                   @PathVariable("calibrationId") Long calibrationId){
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            SessionCalibration sessionCalibration = sessionDuringService.loadSessionCalibration(calibrationId);
            SessionReportWriting sessionReportWriting = sessionReportService.loadReportWriting(sessionCalibration);
            sessionDuringService.supervisorReportSubmit(sessionReportWriting);
            httpResult.success().message("success");
            
        } catch (BusinessException e) {
            httpResult.fail("500").message(e.getMessage());
        } catch (Exception e) {
            httpResult.fail("500").message("failed..");
        }
        
        return httpResult;
    }

}
